var type = ['primary', 'success', 'warning', 'info']

function model(val) {
    if (val === '' || val === null) {
        return '未知'
    } else if (val === 0) {
        return '原创'
    } else if (val === 1) {
        return '转载'
    } else if (val === 2) {
        return '翻译'
    }
}

function TimestampToDate(Timestamp) {

    let date = new Date(Timestamp);
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // 月份是从0开始计数的，所以要加1
    let day = date.getDate();
    // let date1 = new Date(Timestamp);
    // return date1.toLocaleDateString().replace(/\//g, "-") + " " + date1.toTimeString().substr(0, 8);
    return `${year}-${month}-${day}`;
}


function numberTo(number) {
    if (number > 10000) {
        let t = number / 10000
        t = t.toFixed(1)
        return t + 'w+'
    }
    return number
}

function title(val) {
    if (val === '' || val === null || val === undefined) {
        return null
    }
    return val.replace(/#/g, '')
}

// 时间格式化
function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear(),
        hours = d.getHours(),
        minutes = d.getMinutes(),
        seconds = d.getSeconds()

    if (month.length < 2) month = '0' + month
    if (day.length < 2) day = '0' + day
    if (hours.length < 2) hours = '0' + hours
    if (minutes.length < 2) minutes = '0' + minutes
    if (seconds.length < 2) seconds = '0' + seconds

    return [year, month, day].join('-') + ' ' + [hours, minutes, seconds].join(':')
}

// s时间格式化
function formatDateToYYYYMMDD(dateString) {
    var date = new Date(dateString)
    var year = date.getFullYear()
    var month = ('0' + (date.getMonth() + 1)).slice(-2) // 月份是从0开始的，所以加1
    var day = ('0' + date.getDate()).slice(-2) // 获取日，并转换为两位数
    return year + '-' + month + '-' + day
}

// s时间格式化
function formatDateToMMDD(dateString) {
    var date = new Date(dateString)
    // var year = date.getFullYear()
    var month = ('0' + (date.getMonth() + 1)).slice(-2) // 月份是从0开始的，所以加1
    var day = ('0' + date.getDate()).slice(-2) // 获取日，并转换为两位数
    return month + '月' + day
}

// 字符串根据逗号分隔
function stringSplitToArr(text) {
    return text.split(',')
}

// 随机tag颜色
function randomTagToType() {
    var indexType = Math.floor(Math.random() * type.length)
    return type[indexType]
}

/*随机颜色rgb*/
/*随机颜色hsl*/
const RandomColor = function () {
    return "hsl(" +
        Math.round(Math.random() * 360) + "," +
        Math.round(Math.random() * 100) + '%,' +
        Math.round(Math.random() * 80) + '%)';
}
function debounce(func, delay) {
    let timer = null;
    return function () {
        console.log('执行了')
        clearTimeout(timer);
        timer = setTimeout(() => {
            console.log('执行了')
            func.apply(this, arguments);
        }, delay);
    };
}

/*利用Box-Muller方法极坐标形式    使用两个均匀分布产生一个正态分布*/
const Normal = function (mean, sigma) {
    var u = 0.0, v = 0.0, w = 0.0, c = 0.0;
    do {
        //获得两个（-1,1）的独立随机变量
        u = Math.random() * 2 - 1.0;
        v = Math.random() * 2 - 1.0;
        w = u * u + v * v;
    } while (w == 0.0 || w >= 1.0)
    c = Math.sqrt((-2 * Math.log(w)) / w);
    return mean + u * c * sigma;
}
/*
 * 随机拆分一个数
 * params 总和，个数，最大值 {num}
 */

const RandomSplit = function (total, nums, max) {
    let rest = total;
    let result = Array.apply(null, { length: nums })
        .map((n, i) => nums - i)
        .map(n => {
            const v = 1 + Math.floor(Math.random() * (max | rest / n * 2 - 1));
            rest -= v;
            return v;
        });
    result[nums - 1] += rest;
    return result;
}





function getCurrentUserId() {
    const user = localStorage.getItem('user')
    if (user !== null) {
        return JSON.parse(user).id
    }
}

function rulesChAndSpace(text) {
    // 判断是否存在中文的正则表达式
    const containsChineseRegex = /[\u4e00-\u9fa5]/
    // 判断是否存在空格的正则表达式
    const containsSpaceRegex = /\s/

    if (containsChineseRegex.test(text) || containsSpaceRegex.test(text)) {
        return false
    } else {
        return true
    }
}

function isEnglish(text) {
    const regex = /^[A-Za-z0-9]+$/
    if (text === '') {
        return true
    }
    if (regex.test(text)) {
        return text
    } else {
        return ''
    }
}

function diftTime(startTime) {
    const date1 = new Date(formatDateToYYYYMMDD(startTime))
    const date2 = new Date()
    var day = (date2.getTime() - date1.getTime()) / 1000 / 3600 / 60
    if (day >= 365) {
        return (day / 365).toFixed(1) + '年'
    } else {
        return day.toFixed(0) + '天'
    }
}

// 过滤数组，将最近三天的数据获取出来
function getThreeData(arr) {
    // 获取当前日期
    const now = new Date()

    // 获取三天前的日期
    const threeDaysAgo = new Date()
    threeDaysAgo.setDate(now.getDate() - 3)

    // 过滤出最近三天的数据
    const recentThreeDaysData = arr.filter((item) => {
        const createTime = new Date(item.createTime)
        return createTime >= threeDaysAgo && createTime <= now
    })

    return recentThreeDaysData
}

// 根据时间排序
function sortData(data) {
    data.sort((a, b) => {
        return new Date(a.createTime) - new Date(b.createTime)
    })
}

// 获取年份数组
function yearArr() {
    // 获取当前年份
    const currentYear = new Date().getFullYear();
    // 生成年份数组
    const arr = Array.from({ length: 12 }, (_, index) => currentYear - index);
    return arr
}

function delHtmlStyle(text) {
    // if(text||text===''||text==null){
    //   return
    // }
    console.log('-->', text)

    let content = text.replace(/<\/?[^>]*>/g, '') //去除标签
    content = content.replace(/[|]*\n/, '') //去除行尾空格
    return content
}

function formatRelativeTime(date) {
    const now = new Date()
    const diff = Math.abs(now - date)
    const minutes = Math.round(diff / (1000 * 60))
    const hours = Math.round(minutes / 60)

    if (minutes === 1) {
        return '1分钟前'
    } else if (minutes >= 30 && minutes < 60) {
        return '半小时前'
    } else if (hours >= 1 && hours < 2) {
        return '1小时前'
    } else if (hours >= 2 && hours < 3) {
        return '2小时前'
    } else if (hours >= 3 && hours < 4) {
        return '3小时前'
    } else if (hours >= 4 && hours < 12) {
        return '4小时前'
    } else if (hours >= 12 && hours < 24) {
        return '12小时前'
    } else if (hours >= 24 && hours < 24) {
        return '1天前'
    } else if (hours === 24 && hours < 36) {
        return '2天前'
    } else {
        // 你可以根据需要添加更多的条件来处理其他时间差
        var dateString = new Date(date)
        var year = dateString.getFullYear()
        var month = ('0' + (dateString.getMonth() + 1)).slice(-2) // 月份是从0开始的，所以加1
        var day = ('0' + dateString.getDate()).slice(-2) // 获取日，并转换为两位数
        return year + '/' + month + '/' + day
    }
}


export default {
    model,
    title,
    formatDate,
    formatDateToYYYYMMDD,
    stringSplitToArr,
    randomTagToType,
    rulesChAndSpace,
    isEnglish,
    numberTo,
    diftTime,
    getCurrentUserId,
    getThreeData,
    sortData,
    TimestampToDate,
    delHtmlStyle,
    formatRelativeTime,
    formatDateToMMDD,
    yearArr,
    RandomColor,
    Normal,
    RandomSplit,
    debounce
}
